package com.uchedao.vehicledetection.view.widget;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * this class implements registerReceier and unregisterReceiver to avoid re-register and re-unregister exception .Note that you should invoke broadcast's registerReceiver and
 * unregisterReceiver instead of that of activity or fragment's for registration-related purpose .
 * 
 * @author wushan
 * @date 2013-11-7
 */
public abstract class BroadcastReceiver extends android.content.BroadcastReceiver {
    private boolean registered;
    private Context context;

    public void registerReceiver(Context context, IntentFilter intentFilter) {
        if (context == null || registered == true) {
            return;
        }
        context.registerReceiver(this, intentFilter);
        this.context = context;
        registered = !registered;
    }

    public void unregisterReceiver() {
        if (registered) {
            context.unregisterReceiver(this);
            registered = !registered;
        }
    }

    /**
     * returns whether the receiver has been registered
     * 
     * @return
     */
    public boolean isRegistered() {
        return registered;
    }
    
    @Override
    public abstract void onReceive(Context context, Intent intent);
}
